// 处理所有图书数据

var books = [
  {
    bookId: 1,
    bookName: 'JavaScript从入门到放弃',
    time: '2022-10-01',
    des: '描述',
    category: 'web前端'
  },
  {
    bookId: 2,
    bookName: 'MySQL从入门到删库跑路',
    time: '2022-10-01',
    des: '描述',
    category: 'java后端'
  },
  {
    bookId: 3,
    bookName: 'NodeJS从入门到砸服务器',
    time: '2022-10-01',
    des: '描述',
    category: 'web前端'
  },
  {
    bookId: 4,
    bookName: 'ReactJS从入门到老板',
    time: '2022-10-01',
    des: '描述',
    category: 'web前端'
  }
];

var category = [
  {
    categoryId: 1,
    categoryName: 'web前端'
  },
  {
    categoryId: 2,
    categoryName: 'java后端'
  }
];

// 获取所有的图书数据
function getAlBooks() {
  var allBooks = localStorage.getItem('books') ? JSON.parse(localStorage.getItem('books')) : books;
  if (allBooks.length == 0) {
    allBooks = books
  }
  return allBooks;
}

// 获取总数居条数
function getBookCount() {
  return getAlBooks().length;
}

// 分页数据
function getBook(currentPage, pageSize) {
  var allBook = getAlBooks();

  var start = (currentPage - 1) * pageSize; // 数据开始下标

  return allBook.slice(start, start + pageSize);
}

// 通过 id 查找某一条数据
function getBookById(id) {
  var allBook = getAlBooks();
  return allBook.find(function (item) {
    return item.bookId == id
  });
}

// 删除书籍
function delBook(id) {
  var allBook = getAlBooks();
  var resultBook = allBook.filter(function (item) {
    return item.bookId != id;
  });

  localStorage.setItem('books', JSON.stringify(resultBook));
}

// 新增书籍
function addBook(obj) {
  var allBook = getAlBooks();

  allBook.push(obj);

  localStorage.setItem('books', JSON.stringify(allBook));
}

// 编辑书籍
function editBook(obj) {
  var allBook = getAlBooks();

  for (var i = 0; i < allBook.length; i++) {
    if (allBook[i].bookId == obj.bookId) {
      allBook[i].bookName = obj.bookName;
      allBook[i].des = obj.des;
      allBook[i].category = obj.category;
      allBook[i].time = obj.time;
    }
  }

  localStorage.setItem('books', JSON.stringify(allBook));
}

// 所有分类
function getCategory() {
  var allCategory = localStorage.getItem('category') ? JSON.parse(localStorage.getItem('category')) : category;
  if (allCategory.length == 0) {
    allCategory = category
  }
  return allCategory;
}